package org.prism.reflection.proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

//接口
interface IphoneFactory{
    void produceIphone();
}
//被代理类
class FSKIphoneFactory implements IphoneFactory{

    @Override
    public void produceIphone() {
        System.out.println("富士康工厂生产了一批Iphone手机！！");
    }
}
////代理类（自动）
//class ProxyIphoneFactory implements IphoneFactory{
//
//    private IphoneFactory iphoneFactory;
//
//    public ProxyIphoneFactory(IphoneFactory iphoneFactory) {
//        this.iphoneFactory = iphoneFactory;
//    }
//
//    @Override
//    public void produceIphone() {
//        System.out.println("富士康工厂进口了一批Iphone手机零件！！");
//        iphoneFactory.produceIphone();
//        System.out.println("富士康工厂出口了一批Iphone手机！！");
//    }
//}
//代理工厂类
class ProxyFactory{
    //返回一个代理工厂对象
    public static Object getProxyInstance(Object obj){
        MyInvocationHandler myInvocationHandler = new MyInvocationHandler();
        myInvocationHandler.band(obj);
        return Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(),myInvocationHandler);
    }

}
class MyInvocationHandler implements InvocationHandler{
    private Object obj;
    public void band(Object obj){
        this.obj = obj;
    }
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        return method.invoke(obj,args);
    }
}
//动态代理测试
public class DynamicProxyTest {
    public static void main(String[] args) {
        FSKIphoneFactory fskIphoneFactory = new FSKIphoneFactory();
        IphoneFactory proxyInstance = (IphoneFactory) ProxyFactory.getProxyInstance(fskIphoneFactory);
        proxyInstance.produceIphone();
    }
}
